<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/8/16 0016
 * Time: 18:18
 * 财务管理
 */

namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class FinanceController extends AdminbaseController
{

    function _initialize() {
        parent::_initialize();
    }

    /**
     * 用户充值记录
     */
    function water_list(){
        $water_db = M('user_recharge r');

        $mobile=  I("mobile");//支付账号
        $pay_account=  I("pay_account");//支付账号
        $start_time=  I("start_time");//开始时间
        $end_time=  I("end_time");//结束时间
        $pay_method=  intval(I("pay_method"));//支付方式
        $status=  intval(I("status"));//支付方式

        $formget=array('mobile'=>$mobile
        ,'pay_account'=>$pay_account
        ,'pay_method'=>$pay_method,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'status'=>$status);

        $where = "1 ";

        if(!empty($mobile))
            $where = $where." and mobile like '%".$mobile."%'";
        if(!empty($pay_account))
            $where = $where." and pay_account like '%".$pay_account."%'";
        if(!empty($pay_method) && $pay_method!=-1)
            $where = $where.' and pay_method = '.$pay_method;
        if($status!=-1)
            $where = $where.' and status = '.$status;

        if(!empty($start_time))
            $where = $where." and pay_time >= '".$start_time." 00:00:00'";
        if(!empty($end_time))
            $where = $where." and pay_time <= '".$end_time." 23:59:59'";
  
        $count = $water_db->where($where)->join(' db_app_users a on a.user_id = r.user_id')->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }

        $data = $water_db->where($where)
                        ->join(' db_app_users a on a.user_id = r.user_id')
            ->limit($page->firstRow.','.$page->listRows)
            ->order(' pay_time desc')
            ->select();

        $this->assign('datas',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign('formget',$formget);
        $this->display();
    }

    /**
     * 用户订单付款记录
     */
    function pay_list(){
        $water_db = M('order_pay p');

        $pay_account=  I("pay_account");//支付账号
        $start_time=  I("start_time");//开始时间
        $end_time=  I("end_time");//结束时间
        $pay_method=  intval(I("pay_method"));//支付方式

        $formget=array('pay_account'=>$pay_account
        ,'pay_method'=>$pay_method,
            'start_time'=>$start_time,
            'end_time'=>$end_time);

        $where = " 1=1 ";

        if(!empty($pay_account))
            $where = $where." and pay_account like '%".$pay_account."%'";
        if(!empty($pay_method) && $pay_method!=-1)
            $where = $where.' and pay_method = '.$pay_method;

        if(!empty($start_time))
            $where = $where." and pay_time >= '".$start_time." 00:00:00'";
        if(!empty($end_time))
            $where = $where." and pay_time <= '".$end_time." 23:59:59'";

        $count = $water_db->where($where)->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }

//        $Current_page=1；
        $data = $water_db ->where($where)
            ->order(' pay_time desc')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->assign('datas',$data);
        
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->display();
    }
    /**
     * 用户钱包纪录
     */
    function user_purse_list(){
        $water_db = M('user_purse p');

        $mobile=  I("mobile");//电话
        $start_time=  I("start_time");//开始时间
        $end_time=  I("end_time");//结束时间
        $purse_type=  intval(I("purse_type"));//类型

        $formget=array('mobile'=>$mobile
        ,'purse_type'=>$purse_type,
            'start_time'=>$start_time,
            'end_time'=>$end_time);

        $where = " 1=1 ";

        if(!empty($mobile))
            $where = $where." and a.mobile like '%".$mobile."%'";
        if(!empty($purse_type) && $purse_type!=-1)
            $where = $where.' and purse_type = '.$purse_type;

        if(!empty($start_time))
            $where = $where." and change_time >= '".$start_time." 00:00:00'";
        if(!empty($end_time))
            $where = $where." and change_time <= '".$end_time." 23:59:59'";

        $count = $water_db->where($where)->join('db_app_users a ON p.user_id=a.user_id')->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }

//        $Current_page=1；
        $data = $water_db->field('a.mobile,p.*')->join('db_app_users a ON p.user_id=a.user_id')
            ->where($where)
            ->order(' change_time desc')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();

        $this->assign('datas',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->display();
    }

    /**
     * 派单员余额明细
     */
    function pnbalance_list(){
        $water_db = M('dispatch_balance b');

        $mobile=  I("mobile");//电话
        $dispatch_name=  I("dispatch_name");//姓名
        $start_time=  I("start_time");//开始时间
        $end_time=  I("end_time");//结束时间
        $balance_type=  intval(I("balance_type"));//收入类型

        $formget=array('mobile'=>$mobile
           , 'dispatch_name'=>$dispatch_name
        ,'balance_type'=>$balance_type,
            'start_time'=>$start_time,
            'end_time'=>$end_time);

        $where = " 1=1 ";

        if(!empty($mobile))
            $where = $where." and d.mobile like '%".$mobile."%'";
        if(!empty($dispatch_name))
            $where = $where." and d.dispatch_name like '%".$dispatch_name."%'";
        if(!empty($balance_type) && $balance_type!=-1)
            $where = $where.' and balance_type = '.$balance_type;

        if(!empty($start_time))
            $where = $where." and time >= '".$start_time." 00:00:00'";
        if(!empty($end_time))
            $where = $where." and time <= '".$end_time." 23:59:59'";

        $count = $water_db->where($where)->join('db_dispatch d ON b.dispatch_id=d.dispatch_id')->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }

        $data = $water_db->field('d.dispatch_name,d.mobile,b.*')->join('db_dispatch d ON b.dispatch_id=d.dispatch_id')
            ->where($where)
            ->order(' time desc')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();

        $this->assign('datas',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->display();
    }
    /**
     * 派单员提款记录
     */
    function pncash_list(){
        $water_db = M('dispatch_cash c');

        $formget = I('formget');
       // dump($formget);
        $dispatch_name = $formget["dispatch_name"]; //跑客姓名
        $mobile=  $formget["mobile"];//电话
        $company_id = $formget["company_id"]; //公司
        $start_time= $formget["start_time"];//开始时间
        $end_time=  $formget["end_time"];//结束时间
        $status=  intval($formget["status"]);//状态
        if(!$start_time)
            $start_time = date('Y-m-01', strtotime(date("Y-m-d")));
        if(!$end_time)
            $end_time = date('Y-m-d', time());
        $formget=array(
        'dispatch_name'=>$dispatch_name,  
        'mobile'=>$mobile,
        'company_id'=>$company_id,    
        'status'=>$status,
            'start_time'=>$start_time,
            'end_time'=>$end_time);

        $where = " 1=1 ";

         if(!empty($dispatch_name))
            $where = $where." and d.dispatch_name like '%".$dispatch_name."%'";
        if(!empty($mobile))
            $where = $where." and d.mobile like '%".$mobile."%'";
        if(!empty($company_id) && $company_id != 1)
            $where = $where."and d.company_id =".$company_id;
        if($status!=-1)
            $where = $where.' and c.status = '.$status;

        if(!empty($start_time))
            $where = $where." and cash_time >= '".$start_time." 00:00:00'";
        if(!empty($end_time))
            $where = $where." and cash_time <= '".$end_time." 23:59:59'";

        $count = $water_db->where($where)->join('db_dispatch d ON c.dispatch_id=d.dispatch_id')->count();
        //$count = $water_db->where($where)->join('left join db_dispatch d ON c.dispatch_id=d.dispatch_id left join db_company a ON a.company_id=d.company_id')->count();
//        echo $water_db->getLastSql();
//        dump($count);
//        die;
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
        }
                                                                              //join('left join a on a.id = b.id left join b.id = c.id')-
        $data = $water_db->field('d.mobile,c.*,a.company_name,d.dispatch_name,d.cert_number,d.weinxin_openid,d.cash_balance')->join('left join db_dispatch d ON c.dispatch_id=d.dispatch_id left join db_company a ON a.company_id=d.company_id')
            ->where($where)
            ->order('cash_time desc')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
//        echo $water_db->getLastSql();
//        dump($data);
//        die;
        $this->assign('datas',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->display();
    }
    //后台取消审核
    public function pncash_cancelaudit(){
        if(isset($_POST['ids']) && $_GET["audit"]){
            $data["status"]=0;
            $ids=join(",",$_POST['ids']);
            $app_dispatch = M("dispatch_cash");
            $cashs = $app_dispatch->field("GROUP_CONCAT(cash_record_id) as cash_record_id")->where("cash_record_id in ($ids) and status=1")->select();

            if (!$cashs || !$cashs[0]['cash_record_id'])
                $this->success('无需要取消审核的数据');

            $cash_ids = rtrim($cashs[0]['cash_record_id'], ",");

            $up_ret = $app_dispatch->where("cash_record_id in ($cash_ids)")->setField('status',0);

            if ( $up_ret) {
                $this->assign("formget",I('formget'));
                $this->success("取消审核成功！");
            } else {
                $this->error("取消审核失败！");
            }
        }else {
            $this->error('数据传入失败！');
        }

    }
    //后台审核
    public function pncash_audit(){

        if(isset($_POST['ids']) && $_GET["audit"]){
            $app_dispatch = M("dispatch_cash");
            $ids=join(",",$_POST['ids']);
            $cashs = $app_dispatch->field("GROUP_CONCAT(cash_record_id) as cash_record_id")->where("cash_record_id in ($ids) and status=0")->select();

            if (!$cashs || !$cashs[0]['cash_record_id'])
                $this->success('无需要审核的数据');

            $cash_ids = rtrim($cashs[0]['cash_record_id'], ",");

            $up_ret = $app_dispatch->where("cash_record_id in ($cash_ids)")->setField('status',1);

            $this->assign("formget",I('formget'));
            if($up_ret)
                $this->success('审核提现成功');
            else
                $this->error('审核提现失败！');
        }else {
            $this->error('数据传入失败！');
        }

    }
    //打款
    public function pncash_pay(){
        if(isset($_POST['ids']) && $_GET["pay"]){
            $ids=join(",",$_POST['ids']);
            $app_dispatch = M("dispatch_cash");
            $cashs = $app_dispatch->field("GROUP_CONCAT(cash_record_id) as cash_record_id,GROUP_CONCAT(dispatch_id) as dispatch_id")->where("cash_record_id in ($ids) and status=1")->select();

            if (!$cashs || !$cashs[0]['cash_record_id'])
                $this->success('无需要审核的数据');

            $cash_ids = rtrim($cashs[0]['cash_record_id'], ",");
            $pay_time = date('Y-m-d H:i;s',time());
            $up_ret = $app_dispatch->where("cash_record_id in ($cash_ids)")->setField(array('status'=>2,'pay_time'=>$pay_time));

            if($up_ret){
                $dispatch_ids = rtrim($cashs[0]['dispatch_id'], ",");
                $dis_idarr = explode(',',$dispatch_ids);
                if($dis_idarr){
                    foreach ($dis_idarr as $value){
                        $create_ret = create_dispatch_message($value,'提现打款通知','已经打款',date('Y-m-d',time()).'已经打款，请查收');//给跑客发系统消息
                        if(!$create_ret)
                            $this->error("打款消息创建失败");
                    }
                }
                $this->assign("formget",I('formget'));
                $this->success("打款成功");
            }
            else
                $this->error("打款失败");
        }else {
            $this->error('数据传入失败！');
        }

    }
    /**
     * 派单员经验记录
     */
    function pnexp_list(){
        $water_db = M('dispatch_exp e');

        $mobile=  I("mobile");//手机号
        $start_time=  I("start_time");//开始时间
        $end_time=  I("end_time");//结束时间

        $formget=array('mobile'=>$mobile,
            'start_time'=>$start_time,
            'end_time'=>$end_time);

        $where = " 1=1 ";

        if(!empty($mobile))
            $where = $where." and d.mobile like '%".$mobile."%'";

        if(!empty($start_time))
            $where = $where." and time >= '".$start_time." 00:00:00'";
        if(!empty($end_time))
            $where = $where." and time <= '".$end_time." 23:59:59'";

        $count = $water_db->where($where)->join('db_dispatch d ON e.dispatch_id=d.dispatch_id')->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }

        $data = $water_db->field('d.dispatch_name,d.mobile,e.*')->join('db_dispatch d ON e.dispatch_id=d.dispatch_id')
            ->where($where)
            ->order(' time desc')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();

        $this->assign('datas',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->display();
    }


    /**
     * 营业收入
     * income_type=1:平台除去跑腿费后，应该的收入（包含了要分成的金额）
     * income_type=2：平台的真实收入
     */
    function systurnover_list(){
        $water_db = M('systurnover s');

        $order_number=  I("order_number");//用户名称
        $user_name=  I("user_name");//用户名称
        $dispatch_name=  I("dispatch_name");//跑客名称
        $start_time=  I("start_time");//开始时间
        $end_time=  I("end_time");//结束时间

        $formget=array('user_name'=>$user_name,
            'dispatch_name'=>$dispatch_name,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'order_number'=>$order_number);

        $where = " 1 ";

        if(!empty($order_number))
            $where = $where." and o.order_number like '%".$order_number."%'";
        if(!empty($user_name))
            $where = $where." and u.user_name like '%".$user_name."%'";
        if(!empty($dispatch_name))
            $where = $where." and d.dispatch_name like '%".$dispatch_name."%'";

        if(!empty($start_time))
            $where = $where." and date(s.time) >= '".$start_time."'";
        if(!empty($end_time))
            $where = $where." and date(s.time) <= '".$end_time."'";


        $count = $water_db->where($where)->join(' db_dispatch d ON s.dispatch_id=d.dispatch_id')
                        ->join(' db_app_users u ON s.uid=u.user_id')
                        ->join(' db_order o ON o.order_id=s.orderid')
                        ->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }

        $data = $water_db->field('s.id,s.uid,u.user_name,s.dispatch_id,d.dispatch_name,o.order_number,o.real_amount,s.orderid ,s.ordermoney,s.total_income ,s.separate_income'.
                                ',case when s.income_type=1 then o.dispatch_get_money'.
                                '      else 0.00 end as dispatch_get_money'.
                                ',case when s.income_type=1 then FORMAT(total_income-separate_income,2)'.
                                '      else 0.00 end as recommend_separate'.
                                ',s.income_type'.
                             '   ,date(o.order_time) as time')
            ->join(' db_dispatch d ON s.dispatch_id=d.dispatch_id')
            ->join(' db_app_users u ON s.uid=u.user_id')
            ->join(' db_order o ON o.order_id=s.orderid')
            ->limit($page->firstRow.','.$page->listRows)
            ->where($where)
            ->order(' s.time desc')
            ->select();
//        dump($water_db->getLastSql());
        $this->assign('datas',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->display();
    }
    //收入明细查看
    /**
     * 跑客跑腿收入，上级推荐人收入
     * 上级推荐用户收入
     *平台收入 incomemoney（=订单金额-跑腿费-分成费）
     * 跑腿收入 ：跑客余额表
     * 分成（用户钱包表，跑客余额表）: --- 三级分销
     *                                 -- 用户推荐用户
     * 百分比和 N 变量
     *
     * income_type=1:平台除去跑腿费后，应该的收入（包含了要分成的金额）
     * income_type=2：平台的真实收入
     **/
    public function systurnover_see(){
        $id=  intval(I("get.id"));//
        $systurnover_db=M("systurnover s");//创建与数据库表对应的实例对象 --平台营业收入表
        $data = $systurnover_db->where(array("  id" => $id))->find();

        $data = $systurnover_db->field('s.id,s.uid,u.user_name,s.dispatch_id,d.dispatch_name,s.orderid,s.ordermoney	,FORMAT(s.total_income, 2) as total_income,FORMAT(s.separate_income,2) as separate_income,FORMAT(total_income-separate_income,2) as recommend_separate,s.time,o.*')
            ->join(' db_dispatch d ON s.dispatch_id=d.dispatch_id')
            ->join(' db_app_users u ON s.uid=u.user_id')
            ->join(' db_order o ON o.order_id=s.orderid')
            ->where(array("  id" => $id))->find();

        //dump($data['orderid']);

        $recommend_users = distribution($data['uid'],1);
//        dump($recommend_users);
        $this->assign("data", $data);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
        $this->assign("recommend_users", $recommend_users);

        $this->display();// 输出模版文件
    }
        public function testrowad(){
        dump(recommend_order_reward(56,20,34,14.00));
//        dump(distribution(56, '1'));

//        dump(update_user_dispatch_blance(57,1,0.7));
//        dump(update_user_dispatch_blance(19,2,0.7));
    }
    
   //用户积分明细
    /**
      *12.27
     **/
    public function user_points_list()
    {
         $user_points = M("user_points p");
        $mobile = I("mobile");                //电话
        //$time = I("time");      //消息标题
        
        $formget = array(
            'mobile' => $mobile
            //'time' => $time
        );
        
        $where = "1=1";
         if(!empty($mobile))
            $where = $where." and u.mobile like '%".$mobile."%'";
        //if(!empty($time))
          //  $where = $where." and m.time like '%".$time."%'";
        
        $count = $user_points->where($where)->join('db_app_users u ON p.user_id=u.user_id')->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }
        $data = $user_points->field('u.user_name,u.mobile,p.*')->join('db_app_users u ON p.user_id=u.user_id')
            ->where($where)
            ->limit($page->firstRow.','.$page->listRows)
            ->order(' p.points_time desc')
            ->select();
//        dump($data);
//        die;
        $this->assign('datas',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->display();
    }
    
    //用户消息明细
    /**
      *12.27
     **/
    public function user_message_list()
    {
        $user_message = M("user_message m");
        $mobile = I("mobile");                //电话
        $time = I("time");      //消息标题
        
        $formget = array(
            'mobile' => $mobile,
            'time' => $time
        );
        
        $where = "1=1";
         if(!empty($mobile))
            $where = $where." and u.mobile like '%".$mobile."%'";
        if(!empty($time))
            $where = $where." and m.time like '%".$time."%'";
        
        $count = $user_message->where($where)->join('db_app_users u ON m.user_id=u.user_id')->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }
        $data = $user_message->field('u.user_name,u.mobile,m.*')->join('db_app_users u ON m.user_id=u.user_id')
            ->where($where)
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
//        dump($data);
//        die;
        $this->assign('datas',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->display();
    }
    
    //用户经验明细
    public function user_explog_list()
    {
        $user_explog = M("user_explog e");
        $mobile = I("mobile");                //电话
        $time = I("time");      //消息标题
        
        $formget = array(
            'mobile' => $mobile,
            'time' => $time
        );
        
        $where = "1=1";
         if(!empty($mobile))
            $where = $where." and u.mobile like '%".$mobile."%'";
        if(!empty($time))
            $where = $where." and e.time like '%".$time."%'";
        
        $count = $user_explog->where($where)->join('db_app_users u ON e.uid=u.user_id')->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }
        $data = $user_explog->field('u.user_name,u.mobile,e.*')->join('db_app_users u ON e.uid=u.user_id')
            ->where($where)
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
//        dump($data);
//        die;
        $this->assign('datas',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->display();
    }



    /**
     * 结算操作列表
     */
    function settl_operation_list(){
        $water_db = M('dispatch d');

        $formget = I('formget');
        $dispatch_name = $formget["dispatch_name"]; //跑客姓名
        $mobile=  $formget["mobile"];//电话
        $settl_month= $formget["settl_month"];//结算月份
        $company_id=  intval($formget["company_id"]);//状态

        if(!$settl_month)
            $settl_month = date('Y-m',time());

        $formget=array(
            'dispatch_name'=>$dispatch_name,
            'mobile'=>$mobile,
            'company_id'=>$company_id,
            'settl_month'=>$settl_month);

        $where = "is_sign=2 and account_status=1 and d.cash_balance > 0 ";

        if(!empty($dispatch_name))
            $where = $where." and d.dispatch_name like '%".$dispatch_name."%'";
        if(!empty($mobile))
            $where = $where." and d.mobile like '%".$mobile."%'";
        if($company_id && $company_id!=1)
            $where = $where.' and company_id = '.$company_id;

        $count = $water_db->join("left join db_dispatch_settlement s on s.dispatch_id = d.dispatch_id  and settl_month = '".$settl_month."'" )->where($where)->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
        }

        $data = $water_db->field('d.dispatch_id,d.dispatch_name,d.mobile,d.cash_balance,d.company_id,d.company_branch,s.settl_amount,s.settl_time,s.settl_month,s.cash_amount,s.salary_amount,s.cash_balance as settl_cash_balance')
                        ->join("left join db_dispatch_settlement s on s.dispatch_id = d.dispatch_id  and settl_month = '".$settl_month."'" )
            ->where($where)
            ->order(' cash_balance desc,s.settl_time desc')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
//        dump($water_db->getLastSql());
        $this->assign('lists',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->assign('total_count', $count);
        $company = M('company');
        $this->assign('company_data', $company->select());
        $this->display();
    }
   /**
    * 结算操作
    * 结算团队：直属团队，大河团队
    * 用户余额设置为200
    * 用户钱包表，新增一条数据，类别为结算，金额为：用户余额-200
    * 用户结算表，新增一条数据，金额为：用户余额-200，结算时间为当前时间，结算月份为：选择日期
    * 用户系统消息，新增
    * 结算的是没有提现的部分
    * */
    public function settl_operate(){
        if(isset($_POST['ids']) ){
            $data["status"]=0;
            $ids=$_POST['ids'];
            $dispatch_db=M('dispatch');
            $settl_db = M("dispatch_settlement");
            $company_ids = M('company')->field("GROUP_CONCAT(company_id) as company_ids")->where("is_settlement=1")->find();
//            dump($ids);

            $get_param = I('get.');
            $settl_month = $get_param['formget']["settl_month"];
//            dump($settl_month);
            //结算的月份，只能是上一月或本月

            $last_month = date("Y-m", strtotime("-1 months", time()));
            $this_month = date("Y-m", time());
//            dump($last_month);
//            dump($this_month);
           if($settl_month != $last_month && $settl_month != $this_month)
               $this->error('结算月份只能是本月或上一个月');
            $settl_db->startTrans();
            foreach ($ids as $key=>$value){
                $dispatch_obj = $dispatch_db->where('dispatch_id='.$value.' and is_sign=2 and account_status=1 and company_id in('.$company_ids['company_ids'].') and cash_balance > 0 ')->field('dispatch_id,cash_balance')->find();
//                dump($dispatch_obj);
                $settl_obj = $settl_db->where(array('dispatch_id'=>$value,'settl_month'=>I('settl_month')))->find();
                if($dispatch_obj && !$settl_obj){
                    $settl_amount = round(($dispatch_obj['cash_balance']-200)*-1,2);//float类型，相减也会出现无尽小数，如：200.76-200=0.7599999999
//                    dump($settl_amount);
                    $remark = "结算金额（扣除余额）".($settl_amount*-1).'元';
                    if($settl_amount > 0)
                        $remark = "补足履约金200元，结算金额（补增余额）是".$settl_amount.'元';
//                    dump($remark);
                    //本月提现总金额
                    $cash_obj = M('dispatch_cash')->field('sum(cash_amount) as cash_amount')->where("dispatch_id=".$value." and DATE_FORMAT(cash_time, '%Y-%m') = '".$settl_month."'")->find();
//                    dump(M('dispatch_cash')->getLastSql());
//                    dump($cash_obj);
                    $cash_amount = 0;
                    if($cash_obj && $cash_obj['cash_amount'] > 0 )
                        $cash_amount = $cash_obj['cash_amount'];
                    //本月结转工资金额
                    $salary_amount = ($settl_amount*-1) + $cash_amount;
//                    dump($cash_amount);
//                    dump($salary_amount);
//                    exit;

                    //结算表
                    $settl_ret = $settl_db->add(array('dispatch_id'=>$value,'settl_amount'=>$settl_amount,'settl_time'=>date('Y-m-d h:i:s',time()),'settl_month'=>$settl_month,'remark'=>$remark,'cash_amount'=>$cash_amount,'salary_amount'=>$salary_amount,'cash_balance'=>$dispatch_obj['cash_balance']));
                    //钱包表
                    $balance_ret = pnOrderDetail($value,$settl_amount,11, $remark, 0, '结算');//跑客余额表增加记录

                    if($settl_ret&&$balance_ret){
                        //跑客表--余额字段
                        $dis_update=1;
                        if($settl_amount != 0 )
                            $dis_update = $dispatch_db->where(array('dispatch_id'=>$value))->setField(array('cash_balance'=>200));
                        if($dis_update){
                            //跑客消息
                            $msg_ret = create_dispatch_message($value,'结算成功',$remark,$remark);
                            if(!$msg_ret){
                                $settl_db->rollback();
                                $this->error('结算系统消息生成失败');
                            }
                        }
                        else{
                            $settl_db->rollback();
                            $this->error('结算跑客余额失败');
                        }
                    }else{
                        $settl_db->rollback();
                        $this->error('结算失败');
                    }

                }else{
                    $this->error('不符合结算条件！');
                }
            }

            $settl_db->commit();
            $this->success('结算成功', U('Finance/settl_operation_list',array('formget'=>$get_param['formget'])));

        }else {
            $this->error('数据传入失败！');
        }

    }
    /**
     * 补2016年12月结算的数据列表
     */
    function settl_make_list(){
        $water_db = M('dispatch d');

        $formget = I('formget');
        $dispatch_name = $formget["dispatch_name"]; //跑客姓名
        $mobile=  $formget["mobile"];//电话
        $settl_month= $formget["settl_month"];//结算月份
        $company_id=  intval($formget["company_id"]);//状态

        if(!$settl_month)
            $settl_month = date('Y-m',time());

        $formget=array(
            'dispatch_name'=>$dispatch_name,
            'mobile'=>$mobile,
            'company_id'=>$company_id,
            'settl_month'=>$settl_month);

        $where = "is_sign=2 and account_status=1 and d.cash_balance > 0 ";

        if(!empty($dispatch_name))
            $where = $where." and d.dispatch_name like '%".$dispatch_name."%'";
        if(!empty($mobile))
            $where = $where." and d.mobile like '%".$mobile."%'";
        if($company_id && $company_id!=1)
            $where = $where.' and company_id = '.$company_id;

        $count = $water_db->join("left join db_dispatch_settlement s on s.dispatch_id = d.dispatch_id  and settl_month = '".$settl_month."'" )->where($where)->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
        }

        $data = $water_db->field('d.dispatch_id,d.dispatch_name,d.mobile,d.cash_balance,d.company_id,d.company_branch,s.settl_amount,s.settl_time,s.settl_month,s.cash_amount,s.salary_amount,s.cash_balance as settl_cash_balance')
            ->join("left join db_dispatch_settlement s on s.dispatch_id = d.dispatch_id  and settl_month = '".$settl_month."'" )
            ->where($where)
            ->order(' cash_balance desc,s.settl_time desc')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
//        dump($water_db->getLastSql());
        $this->assign('lists',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->assign('total_count', $count);
        $company = M('company');
        $this->assign('company_data', $company->select());
        $this->display();
    }
    /**
     * 补2016年12月结算操作
     * 结算团队：直属团队
     * 用户钱包表，新增一条数据，类别为结算，金额为：用户余额-200
     * 用户结算表，新增一条数据，金额为：用户余额-200，结算时间为当前时间，结算月份为：选择日期
     * 用户系统消息，新增
     * 结算的是没有提现的部分
     * */
    public function settl_make_operate(){

            $dispatch_id = I("id");
            $settl_amount = I("counts");
//            dump($dispatch_id);
//            dump($settl_amount);
            $data["status"]=0;
            $ids=$_POST['ids'];
            $dispatch_db=M('dispatch');
            $settl_db = M("dispatch_settlement");
            $company_ids = M('company')->field("GROUP_CONCAT(company_id) as company_ids")->where("is_settlement=1")->find();

            $get_param = I('get.');

            //结算的月份，只能是上一月
            $last_month = date("Y-m", strtotime("-1 months", time()));

//            dump($last_month);

            $settl_db->startTrans();

        $dispatch_obj = $dispatch_db->where('dispatch_id='.$dispatch_id.' and is_sign=2 and account_status=1 and company_id in('.$company_ids['company_ids'].') and cash_balance > 0 ')->field('dispatch_id,cash_balance')->find();
//                dump($dispatch_obj);
        $settl_obj = $settl_db->where(array('dispatch_id'=>$dispatch_id,'settl_month'=>I('settl_month')))->find();
        if($dispatch_obj && !$settl_obj){
            //本月提现总金额
            $cash_obj = M('dispatch_cash')->field('sum(cash_amount) as cash_amount')->where("dispatch_id=".$dispatch_id." and DATE_FORMAT(cash_time, '%Y-%m') = '".$last_month."'")->find();
//            dump(M('dispatch_cash')->getLastSql());
//            dump($cash_obj);
            $cash_amount = 0;
            if($cash_obj && $cash_obj['cash_amount'] > 0 )
                $cash_amount = $cash_obj['cash_amount'];
            //本月结转工资金额
            $salary_amount = round($settl_amount-$cash_amount,2);
//            dump($cash_amount);
//            dump($salary_amount);
            $settl_amount = $salary_amount * -1;
            $remark = "【补结算月份是".$last_month."的结算明细】结算金额（扣除余额）".$salary_amount.'元';
            if($settl_amount > 0)
                $remark = "【补结算月份是".$last_month."的结算明细】补足履约金200元，结算金额（补增余额）是".$settl_amount.'元';
//            dump($remark);

            //结算表
            $settl_data = array('dispatch_id'=>$dispatch_id,
                    'settl_amount'=>$settl_amount,
                    'settl_time'=>$last_month.'-30 10:00:00',
                    'settl_month'=>$last_month,
                    'remark'=>$remark,
                    'cash_amount'=>$cash_amount,
                    'salary_amount'=>$salary_amount,
                    'cash_balance'=>$dispatch_obj['cash_balance']);
            $settl_ret = $settl_db->add($settl_data);

            //钱包表
            $dispatch_balance = M('dispatch_balance');
            $data = array(
                'dispatch_id' => $dispatch_id,
                'balance_amount' => $settl_amount,
                'balance_type' => 11,
                'change_memo' => $remark,
                'time' => $last_month.'-30 10:00:00',
                'remark' =>  '【补】结算'
            );
            $balance_ret = $dispatch_balance->add($data);

            //消息表
            $msg_db = M('disptch_message');
            $data = array(
                'dispatch_id'=>$dispatch_id,
                'message_id'=>0,
                'title'=>'结算成功',
                'intro'=>$remark,
                'content'=>$remark,
                'time'=>$last_month.'-30 10:00:00'
            );
            $msg_ret = $msg_db->add($data);

            if($settl_ret && $balance_ret && $msg_ret){
                $settl_db->commit();
                $this->success('结算成功', U('Finance/settl_make_list',array('formget'=>$get_param['formget'])));
            }else{
                $settl_db->rollback();
                $this->error('结算失败');
            }
        }else{
            $this->error('不符合结算条件！');
        }
    }

    /**
     * 跑客钱包类别合计
     * 在打款时方便查阅
     */
    function balance_list(){
        $dispatch_db = M('dispatch_balance b');

        $dispatch_id = I("dispatch_id"); //跑客姓名
        $start_time=  I("start_time");//开始时间
        $end_time=  I("end_time");//结束时间

        $where = "1 ";

        if($dispatch_id && $dispatch_id!=-1)
            $where = $where.' and b.dispatch_id = '.$dispatch_id;
        if(!empty($start_time))
            $where = $where." and b.time >= '".$start_time." 00:00:00'";
        if(!empty($end_time))
            $where = $where." and b.time <= '".$end_time." 23:59:59'";


        $data = $dispatch_db->field('b.dispatch_id,b.balance_type,	case when b.balance_type =4 	then sum(b.balance_amount*-1) '.
            'ELSE sum(b.balance_amount) end as balance_amount')
            ->where($where)
            ->group(" b.dispatch_id,b.balance_type")
            ->order(' b.balance_type')
            ->select();
       // dump($data);
        $sum_data = $dispatch_db->field('sum(case when b.balance_type =4 	then b.balance_amount*-1 '.
						                'ELSE b.balance_amount end) as balance_amount')
                            ->where($where)
                            ->group(" b.dispatch_id")
                            ->select();

        if($start_time && $end_time)
            $titleName = $start_time.'至'.$end_time.'钱包金额';
        elseif (!$start_time && !$end_time)
            $titleName = '从始至今的钱包金额';
        elseif(!$start_time && $end_time)
            $titleName = '从始至'.$end_time.'的钱包金额';
        elseif($start_time && !$end_time)
            $titleName = '从'.$start_time.'至今的钱包金额';

//        dump($water_db->getLastSql());
        
        $this->assign('lists',$data);
        $this->assign('titleName',$titleName);
        $this->assign('sum_data',$sum_data[0]['balance_amount']);
        $this->display();
    }
     /**
     * 跑客钱包类别合计
     * 在打款时方便查阅
     */
    function cash_list(){
        $dispatch_db = M('dispatch_balance b');

        $dispatch_id = I("dispatch_id"); //跑客姓名
        $start_time=  I("start_time");//开始时间
        $end_time=  I("end_time");//结束时间

        $where = "1 ";

        if($dispatch_id && $dispatch_id!=-1)
            $where = $where.' and b.dispatch_id = '.$dispatch_id;
        if(!empty($start_time))
            $where = $where." and b.time >= '".$start_time." 00:00:00'";
        if(!empty($end_time))
            $where = $where." and b.time <= '".$end_time." 23:59:59'";


        $data = $dispatch_db->field('b.dispatch_id,b.balance_type,	case when b.balance_type =4 	then sum(b.balance_amount*-1) '.
            'ELSE sum(b.balance_amount) end as balance_amount')
            ->where($where)
            ->group(" b.dispatch_id,b.balance_type")
            ->order(' b.balance_type')
            ->select();
       // dump($data);
        $sum_data = $dispatch_db->field('sum(case when b.balance_type =4 	then b.balance_amount*-1 '.
						                'ELSE b.balance_amount end) as balance_amount')
                            ->where($where)
                            ->group(" b.dispatch_id")
                            ->select();

        if($start_time && $end_time)
            $titleName = $start_time.'至'.$end_time.'钱包金额';
        elseif (!$start_time && !$end_time)
            $titleName = '从始至今的钱包金额';
        elseif(!$start_time && $end_time)
            $titleName = '从始至'.$end_time.'的钱包金额';
        elseif($start_time && !$end_time)
            $titleName = '从'.$start_time.'至今的钱包金额';

//        dump($water_db->getLastSql());
        //查找跑客的押金信息
        $result_data = $dispatch_db->field('b.balance_amount ,b.change_memo ,b.time')
                            ->join('db_dispatch as d on d.dispatch_id = b.dispatch_id')
                                 ->where(array('b.dispatch_id'=>$dispatch_id,'balance_type'=>7,'d.is_sign'=>2))
                                   ->select();
       // dump($result_data);
       // echo $dispatch_db->getLastSql();
        $this->assign('lists',$data);
        $this->assign('result_data',$result_data);
        $this->assign('titleName',$titleName);
        $this->assign('sum_data',$sum_data[0]['balance_amount']);
        $this->display();
    }
}